// pages/wristDetail/index.js
// 获取应用实例
const app = getApp()
const config = app.globalData;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgurl:'',
        equipmentNo: '',
        showTip: false,

        // 是否在线
        isOnline: false,
        // 是否佩戴
        isWear: false,

        // 是否警报
        isAlarm: false,
        isMute: false,
        audioContext: null,

        // 是否故障
        isFault: false,
        // 是否插入体温传感器
        tempSensor: false,

        timer: null,
        wristData: {},

        showPopup: false,
        popupTitle: '',
        popupMsg: '',
        popupIcon: '',
    },
    showPopup() {
        this.setData({ showTip: true });
    },
    onClose() {
        this.setData({ showTip: false });
    },
    // 查看历史
    handlerHis(){
        if(config.userInfo.phone == null){
            this.goLogin()
        } else {
            wx.navigateTo({
                url: '../../pages/wristhistory/index',
            })
        }
    },
    // 故障
    handlerError(){
      this.setData({
        showPopup: true,
        popupTitle: "设备故障",
        popupMsg: "请联系客服：12138",
        popupIcon: "../../size/image/phcall.png",
      });
    },
    goLogin(){
        wx.navigateTo({
            url: '../../pages/login/index',
        })
    },

    // 获取数据
    getData(){
        let that = this;
        that.requestData();
        that.setData({
            timer: setInterval(() => {
                that.requestData()
            }, 5000)
        });
    },

    // 请求数据
    requestData(){
        let equipmentNo = config.userInfo.equipmentNo;
        let equipmentType = config.userInfo.equipmentType;
        let that = this;
        wx.request({
            url: config.url+'api/equipment/getRealtimeData?equipmentNo='+equipmentNo+'&phone='+app.globalData.userInfo.phone+'&equipmentType='+equipmentType,
            success(res){
                let data = res.data.data;
                data.hr = data.hr?data.hr:0;
                data.spo2 = data.spo2?data.spo2:0;
                data.temp = data.temp?data.temp/10:0;
                data.batpt = data.batpt?data.batpt:0;
                that.setData({
                    wristData: data,
                });
                that.getStatus(data);
            }
        })
    },

    getStatus(data){
        let that = this;
        // 是否佩戴(穿戴状态:0-未佩戴手环;1-已佩戴手环)
        let wearStatus = data.wState == 1;
        // 体温传感器状态（0-插入，1-未插入）
        let tempSensor = data.tempSensorStatus == 0;
        // 是否故障（0-有故障，1-无故障）
        let faultState = data.restHeart == 0;
        // 是否在线(设备状态 null=未使用；0=在线；1=离线；)
        let onlineStatus = data.equipmentStatus == 0;        

        that.setData({
            isWear: wearStatus,
            isOnline: onlineStatus,
            isFault: faultState,
            tempSensor: tempSensor,
        });

        /**
         * 判断报警
         * 在线及佩戴状态下
         * 脉率：中间值80、下限50、上限110
         * 血氧：中间值95、下限90
         * 体温：中间值37、下限36、上限38
         */
        if(wearStatus && onlineStatus
          && (data.hr < 50 || data.hr > 110
          || data.spo2 < 90 || data.spo2 > 100
          || (tempSensor && data.temp < 36) || (tempSensor && data.temp > 38))
        ) {
            // 警报状态
            that.setData({
                isAlarm: true
            });

            // 判断是否静音
            if(! that.data.isMute && that.data.isOnline && that.data.isWear) {
              // 不是静音状态下，播放铃声
              that.data.audioContext.play();
            } else {
              that.data.audioContext.pause();
            }
          } else {
            // 警报状态
            that.setData({
                isAlarm: false
            });
            that.data.audioContext.pause();
          }

    },
    closeRing(){
        let that = this;
        // 开启静音
        app.globalData.isMute = true;
        that.setData({
            isMute: true,
        });
        // 停止播放铃声
        that.data.audioContext.pause();
    },
    openRing(){
      let that = this;
      // 关闭静音
      app.globalData.isMute = false;
      that.setData({
        isMute: false
      });
      // 如果警报状态，直接响铃
      if(that.data.isAlarm && that.data.isOnline && that.data.isWear){
        that.data.audioContext.play();
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            imgurl: config.imgurl,
            equipmentNo: config.userInfo.equipmentNo,
            isMute: config.isMute,
        })

        let audioContext = wx.createInnerAudioContext();
        audioContext.src = config.audiourl;
        audioContext.loop = true;
        this.setData({
            audioContext: audioContext
        });

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.getData()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
      this.data.audioContext.pause();
      clearInterval(this.data.timer);
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
      this.data.audioContext.pause();
      clearInterval(this.data.timer);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})